# coding: utf-8

import csv
import pandas as pd


def readcvs():
	csvfile = open(r'data\airport_gz_passenger_predict.csv', 'rb')
	reader = csv.reader(csvfile)

	for line in reader:
		print line

	csvfile.close()


def _map(data, exp):
	for index, row in data.iterrows():   # 获取每行的index、row
		for col_name in data.columns:
			row[col_name] = exp(row[col_name])  # 把结果返回给data
	return data


def _1map(data, exp):
	# 把结果转换成2级list
	_data = [[exp(row[col_name])for col_name in data.columns]for index, row in data.iterrows()]
	return _data



def partitioncvs():
	data = pd.read_csv(r'data\001.csv')  # WIFI_AP_Passenger_Records_chusai_1stround
	wifilist = list(set(data.WIFIAPTag))
	i = '1'
	for wifi in wifilist[0:5]:
		data[data.WIFIAPTag == wifi].to_csv(i + " wifi.csv ")
		i += '1'


# 读取同一个tag 的 cvs
def readonecvs(data=None):

	resultset = {}
	for line in data:
		stime = line[2][0:15]
		print stime
		if stime not in resultset.keys():
			resultset[stime] = int(line[1])
		else:
			resultset[stime] += int(line[1])
		# pass
	print resultset

	return resultset


def maptolist(resultset, wifitag):
	resullist = []

	for key in resultset.keys():
		li = list()
		li.append(resultset[key] * 1.0 / 10)
		li.append(wifitag)
		li.append(key)
		resullist.append(li)

	return resullist


def writelisttocvs(filename, resullist):
	csvfile = file('data\\' + filename, 'wb')
	writer = csv.writer(csvfile)

	writer.writerow(['passengerCount', 'WIFIAPTag', 'slice10min'])
	writer.writerows(resullist)




def partcvs():
	data = pd.read_csv(r'data\WIFI_AP_Passenger_Records_chusai_1stround.csv')
	wifilist = list(set(data.WIFIAPTag))
	results = []

	for wifi in wifilist:
		subdata = data[data.WIFIAPTag == wifi]
		subdata = _1map(subdata, lambda ele: ele)

		print subdata
		resultset = readonecvs(subdata)
		# 写入 cvs
		resultlist = maptolist(resultset, wifi)

		# 把所有的 wifitag 放在一起
		results.extend(resultlist)


	writelisttocvs("result.csv", results)

if __name__ == "__main__":
	# inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
	# df = pd.DataFrame(inp)
	# temp = _map(df, lambda ele: ele+1 )
	# print temp  #  pandas 对象
	#
	# _temp = _1map(df, lambda ele: ele + 1)
	#
	# print _temp
	partcvs()
